#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2/10/16 base trans. wrote by srcdog on 20th, April, 2009
# ld elements in base 2, 10, 16.

import os,sys

# global definition
# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]

# 二进制 to 十进制
def bin2dec(string_num):
    #print 'string_num=' + string_num
    return str(int(string_num, 2))

# 十进制 to 二进制
def dec2bin(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num,rem = divmod(num, 2)
        mid.append(base[rem])
    if len(mid) == 0 : mid.append(0)
    ret = ''.join([str(x) for x in mid[::-1]])
    #print '##### ' + ret + ' #####'
    return ret

def mask2bin( mask ):
    if mask > 0 and mask < 33 :
        full_1 = '11111111'+'11111111'+'11111111'+'11111111'
        full_0 = '00000000'+'00000000'+'00000000'+'00000000'
        return full_1[:mask]+full_0[mask:]
    else:
        return ""

def to32b(ip):
    full_0 = '00000000'+'00000000'+'00000000'+'00000000'
    first1 = ip.find('1')
    if first1 == -1 :
        return full_0
    else :
        return full_0[:(32-len(ip))] + ip


def toIpStr( ip_in ):
    d = '.'
    #print "ip_in=" + ip_in
    ip = to32b(ip_in)
    #print "ip=   " + ip

    ip_out = bin2dec(ip[:8])+d+bin2dec(ip[8:16])+d+bin2dec(ip[16:24])+d+bin2dec(ip[-8:])
    return ip_out

def ip2bin( ip ):
    full_0 = '00000000'
    parts = ip.split('.')
    p1 = dec2bin(parts[0])
    p1 = full_0[:(8-len(p1))] + p1

    p2 = dec2bin(parts[1])
    p2 = full_0[:(8-len(p2))] + p2

    p3 = dec2bin(parts[2])
    p3 = full_0[:(8-len(p3))] + p3

    #print parts
    p4 = dec2bin(parts[3])
    p4 = full_0[:(8-len(p4))] + p4
    
    binstr =  p1+p2+p3+p4
    return binstr

def getMaxIP(ip, mask):
    full_1 = '11111111'+'11111111'+'11111111'+'11111111'
    
    binIPStr = ip2bin( ip )
    binMaskStr = mask2bin( mask )
    
    maxIP = binIPStr[:mask] + full_1[mask:]
    return maxIP


class IpInfo(object):
    minIP = 0
    maxIP = 0

    startIP = ''
    endIP = ''

    mask = 0
    isp = ''
    ispDetail = ''
    desc = ''
    
    def __init__(self, info):
        self.startIP = info[0].strip()
        endDefine = str(info[1]).strip()
        self.isp = info[2].strip()
        self.ispDetail = info[3].strip()
        self.desc = info[4].strip()

        startIpInBin = ip2bin(self.startIP)
        endIpInBin = ''
        if str.isdigit(endDefine) :
            self.mask = int(endDefine)
            endIpInBin = getMaxIP(self.startIP, self.mask)
            self.endIP = toIpStr(endIpInBin)
        else :
            endIpInBin = ip2bin(endDefine)
        
        self.minIP = int(startIpInBin, 2)
        self.maxIP = int(endIpInBin, 2)
        #print self.minIP
        #print self.maxIP
        print toIpStr(dec2bin(str(self.minIP))) + " " + toIpStr(dec2bin(str(self.maxIP)))
           
        
    def inThere(self,ip):
        
        iIP = int( ip2bin(ip), 2)
        if iIP <= self.maxIP and iIP >= self.minIP :
            return True
        else :
            return False

def getIpInfo():
    cmccIpFile = open('cmcc_ip.txt')
    cmccIpList = cmccIpFile.readlines()

    cmccIpInfoList = []
    for cmccIp in cmccIpList :
        #print cmccIp
        cmccIpInfo = IpInfo(cmccIp)
        cmccIpInfoList.append(cmccIpInfo)

    cmccIpFile.close()


    ispFile = open('isp.txt', 'w')

    pingResultFile = open('SubDomainResult.txt')
    pingResultList = pingResultFile.readlines()
    for pingResult in pingResultList :
        #print "LINE: " + pingResult
        if cmp(pingResult.strip(), '') == 0 :
            print 'Blank Line'
            continue

        tempArray = pingResult.split('\t')
        #print "Array: " + str(tempArray)
        notfoundFlag = True
        if len(tempArray) > 1 :
            for ipInfo in cmccIpInfoList :
                if ipInfo.inThere( tempArray[1] ) :
                    strTemp = tempArray[0] + '\t' + tempArray[1] + '\t' + ipInfo.isp + '\t' + ipInfo.desc + '\n'
                    ispFile.writelines(strTemp) 
                    print strTemp  
                    notfoundFlag = False
                    break
        else :
            strTemp = 'Error Line: ' + pingResult[:-2] + '\n'
            ispFile.writelines(strTemp) 
            print strTemp
            notfoundFlag = False

        if notfoundFlag :
            strTemp = tempArray[0] + '\t' + tempArray[1] + '\t外网\t无备注' + '\n' 
            ispFile.writelines(strTemp) 
            print strTemp

    pingResultFile.close()
    ispFile.close()



#strIP = '192.168.1.1/24/内网'
#ipinfo = IpInfo( strIP )
#print ipinfo.inThere('192.168.0.1') 
#print ipinfo.inThere('192.168.1.0')
#print ipinfo.inThere('192.168.1.1')
#print ipinfo.inThere('192.168.1.254')
#print ipinfo.inThere('192.168.1.255')
#print ipinfo.inThere('192.168.2.0') 
#print ipinfo.isp


